package com.mocha.bss.domain.rbac.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mocha.bss.domain.rbac.repository.entity.RoleAdmEntity;
import com.mocha.bss.domain.rbac.repository.mapper.RoleAdmMapper;
import com.pinghua.mocha.basics.setting.MochaSettings;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author songkui
 * @since 2025-04-08
 */
@Service
public class RoleAdmRepository extends ServiceImpl<RoleAdmMapper, RoleAdmEntity> {


    public RoleAdmEntity getByRelatedId(Long userId) {
        return this.lambdaQuery().eq(RoleAdmEntity::getRelatedId, userId).one();
    }

    public String getAdmByRelatedId(Long userId) {
        List<RoleAdmEntity> list = this.lambdaQuery().select(RoleAdmEntity::getAdmIds).eq(RoleAdmEntity::getRelatedId, userId).list();
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }

        Set<String> setStr = list.stream().map(RoleAdmEntity::getAdmIds).collect(Collectors.toSet());
        Set<String> set = new HashSet<>();
        for (String str : setStr) {
            if (StrUtil.isNotEmpty(str)) {
                if (str.contains(",")) {
                    set.addAll(strToSet(str));
                } else {
                    set.add(str);
                }
            }
        }
        String res = StrUtil.join(",", set);

        return  res.contains(MochaSettings.ALL) ? MochaSettings.ALL : res;
    }

    private Set<String> strToSet(String codes) {
        return Arrays.stream(codes.split("\\s*,\\s*"))
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toSet());
    }

}

